/*
 Copyright 2013 Abdulla Abdurakhmanov (abdulla@latestbit.com)
 Original sources are available 
 at https://code.google.com/p/backbone-editable-views-plugin/

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
(function () {
	'use strict';

	Backbone.EditableViewsManager = Backbone.Model.extend({
		defaults : function() {
			return {
				editorTemplateId : "#backbone-view-editor-template",
				editableViewsSelector : ".backbone-editable-view",
				editableViewsAttrId : "data-backbone-editor-source-templateId",
				initEditorFunc : this.defaultInitEditor,
				runEditorFunc : this.defaultRunEditor,
				destroyEditorFunc : this.defaultDestroyEditor,
				compileTemplateFunc : this.defaultCompileTemplate,
				renderTemplateFunc : this.defaultRenderTemplate,
				saveViewFunc : this.defaultSaveView
			};
		},

		initialize : function() {
			_.extend(this, Backbone.Events);
			_.bindAll(this, 
				"defaultInitEditor", "runEditor", "defaultRunEditor", "destroyEditor", "defaultDestroyEditor",
				"compileTemplate", "renderTemplate",
				"startEditMode", "endEditMode", 
				"saveViewCallback");
			this.editorTemplate = this.compileTemplate(this.get("editorTemplateId"));
			this.get("initEditorFunc").call(this);
		},


		templateIdToSelector : function(templateId) {
			return this.get("editableViewsSelector") + "["+this.get("editableViewsAttrId")+"='"+templateId+"']";
		},

		defaultInitEditor : function() {
			console.log("Initializing TinyMCE");
		},

		defaultRunEditor : function(templateId) {
			var selector = this.templateIdToSelector( templateId );
			console.log("Running TineMCE default editor on "+selector+" ...");
			tinymce.init({
				selector: selector, //this.get("editableViewsSelector"),
				menubar : false,
				plugins: "link image code save",
				toolbar: "save undo redo | styleselect | bold italic | link image | code",
				entity_encoding: "raw",
				save_enablewhendirty: true,
				save_onsavecallback: this.saveViewCallback,
				inline : true,
				cleanup_on_startup : true
			});
		},

		runEditor : function(templateId) {
			this.get("runEditorFunc").call(this, templateId);
		},

		defaultDestroyEditor : function(templateId) {
			var selector = this.templateIdToSelector( templateId);
			console.log("Destroying editor for "+selector);
			tinymce.remove({selector : selector});
			//tinymce.remove($(selector));
			tinyMCE.EditorManager.remove();
		},
	
		destroyEditor : function(templateId) {
			this.get("destroyEditorFunc").call(this, templateId);
		},

		compileTemplate : function(selector) {
			return this.get("compileTemplateFunc").call(this,selector);
		},

		defaultCompileTemplate : function(selector) {
			return Handlebars.compile($(selector).html());
		},

		renderTemplate : function(template, context) {
			return this.get("renderTemplateFunc").call(this, template, context);
		},

		defaultRenderTemplate : function(template, context) {
			return template(context);
		},

		startEditMode : function() {
			this.trigger("startEditMode", this);
		},

		endEditMode : function() {
			this.trigger("endEditMode", this);
			this.destroyEditor("*");
		},

		saveViewCallback : function(htmlObj) {
			var templateId = htmlObj.getElement().getAttribute("data-backbone-editor-source-templateId");
			$(templateId).html(htmlObj.getContent());
			this.defaultSaveView(templateId, htmlObj.getContent());
		},

		defaultSaveView : function(templateId, content) {
			console.log("Default save callback triggered for "+templateId+"!. New content: "+content);
		}
	});

	Backbone.EditableView = Backbone.View.extend({

		initializeEditableView : function() {
			_.bindAll(this, "onStartEditMode", "onEndEditMode", "render");
			this.renderInEditMode = false;
			this.renderTemplate = this.options.editableViewsManager.renderTemplate;
			this.runEditor = this.options.editableViewsManager.runEditor;
			this.destroyEditor = this.options.editableViewsManager.destroyEditor;
			this.editorSelector = this.options.editableViewsManager.get("editableViewsSelector");

			this.template = this.options.editableViewsManager.compileTemplate( this.templateId );
			this.editorTemplate = this.options.editableViewsManager.editorTemplate;
			this.listenTo(this.options.editableViewsManager, "startEditMode", this.onStartEditMode, this);
			this.listenTo(this.options.editableViewsManager, "endEditMode", this.onEndEditMode, this);
		},		

		initialize: function() {
			this.initializeEditableView();
			Backbone.View.prototype.initialize.call(this);
		},

		remove : function() {
			this.stopListening();
			Backbone.View.prototype.remove.call(this);
		},

		onStartEditMode : function(mgr) {
			this.renderInEditMode = true;
		},

		onEndEditMode : function(mgr) {
			this.renderInEditMode = false;
		},

		render : function() {
			if(!this.renderInEditMode) {
				this.destroyEditor(this.templateId);
				console.log("Render in usual mode");
				this.$el.html(this.renderTemplate(this.template, this));
			}
			else {
				console.log("Render in edit mode");
				this.$el.html(this.renderTemplate(this.editorTemplate, this));
				this.runEditor(this.templateId);
			}
			return this;
		},

		templateSource : function() {
			return $(this.templateId).html();
		}
		
	});

		
}());
